package Demo;

import javax.swing.*;
import java.awt.Point;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class Demo90 {
    public static void main(String[] args) throws Exception {
        JFrame jf = new JFrame();
        jf.setBounds(200, 200, 500, 500);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.setBackground(Color.WHITE);
        Container contentPane = jf.getContentPane();
        //************************************************
        paintLine p = new paintLine();
        //*****************************************
        contentPane.add(p);
        jf.setVisible(true);
    }
}

class paintLine extends JPanel {
    boolean flag = false;

    public paintLine() {
        mouse m = new mouse();
        this.addMouseListener(m);
        this.addMouseMotionListener(m);
    }
int i=0;
    class mouse extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            flag = true;
            all.add(e.getPoint());
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            flag = false;
            all.clear();
            i++;
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            all.add(e.getPoint());
            repaint();
        }
    }

    List<Point> all = new ArrayList<>();

    @Override
    protected void paintComponent(Graphics g) {
        if (all.size() < 2) {
            return;
        }
        Point p0, p1;
        for (int j = 0; j <i ; j++) {
            p0 = all.get(0);
            for (int i = 1; i < all.size(); i++) {
                p1 = all.get(i);
                g.drawLine(p0.x, p0.y, p1.x, p1.y);
                p0 = p1;
            }
        }

    }
}

